package com.xinfu.newproject.ui.carFee.add_parking;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alley.van.VanGogh;
import com.alley.van.helper.VanCropType;
import com.alley.van.helper.VanMediaFilter;
import com.alley.van.helper.VanMediaType;
import com.alley.van.model.VanConfig;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xinfu.newproject.R;
import com.xinfu.newproject.activity.ResidentCertificationActivity;
import com.xinfu.newproject.adapter.matter_repair_adapter.RepairImageAdapter;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.certifition.ResidentBean;
import com.xinfu.newproject.bean.certifition.ResidentCertificationBean;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.bean.park_bean.bean.AddMonthCarBean;
import com.xinfu.newproject.bean.park_bean.bean.CheckMonthParkBean;
import com.xinfu.newproject.bean.park_bean.bean.FeeListBean;
import com.xinfu.newproject.bean.park_bean.bean.GetMonthCarListBean;
import com.xinfu.newproject.bean.park_bean.bean.GetParkingBean;
import com.xinfu.newproject.bean.park_bean.bean.PaymentsBean;
import com.xinfu.newproject.bean.paycost.bean.ComputeParkingBean;
import com.xinfu.newproject.bean.up_image.UpImageBean;
import com.xinfu.newproject.contants.Contants;
import com.xinfu.newproject.presenter.ParkingPresenter;
import com.xinfu.newproject.presenter.UpImagePresenter;
import com.xinfu.newproject.test.GifSizeFilter;
import com.xinfu.newproject.test.GlideImageLoader;
import com.xinfu.newproject.test.VanToast;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.GetImagePathUtil;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.util.WHelperUtil;
import com.xinfu.newproject.view.IView;
import com.xinfu.newproject.widget.CustomClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.xinfu.newproject.contants.Constant.LOGIN;

public class AddMonthCardParkFragment extends BaseActivity implements IView.IParkingView, RepairImageAdapter.RemoveOnClickListener, IView.IUpImageView {

    @BindView(R.id.head_text)
    TextView titleTv;

    @BindView(R.id.head_back)
    ImageView backIv;

    @BindView(R.id.layout_next_step_tv)
    TextView submitTv;

    @BindView(R.id.fragment_add_month_card_park_community)
    TextView communityEt;

    @BindView(R.id.fragment_add_month_card_park_car)
    TextView carEt;

    @BindView(R.id.fragment_add_month_card_park_project)
    TextView projectEt;

    @BindView(R.id.fragment_add_month_card_park_name)
    EditText nameEt;

    @BindView(R.id.fragment_add_month_card_park_phone)
    EditText phoneEt;

    @BindView(R.id.layout_up_image_tv)
    TextView imageTv;

    @BindView(R.id.layout_up_image_rv)
    RecyclerView imageRecyclerView;

    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_CODE_CAMERA = 32;
    private RepairImageAdapter repairImageAdapter;
    private int isImage = 0;
    private ArrayList<String> imageList = new ArrayList<>();

    private ParkingPresenter parkingPresenter = new ParkingPresenter(this);
    private UpImagePresenter upImagePresenter = new UpImagePresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_add_month_card_park);
        ButterKnife.bind(this);
        registerBack();
        setActivityTitle("添加月卡车");
        initViewBind();
        initLisener();

    }

    private void initLisener() {
        submitTv.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isLogin()) {
                    if (TextUtils.isEmpty(projectEt.getText()) || TextUtils.isEmpty(nameEt.getText()) || TextUtils.isEmpty(phoneEt.getText())) {
                        BToast.showText(AddMonthCardParkFragment.this, "请填写完整信息");
                    } else {
                        if (!WHelperUtil.isMobileRight(AddMonthCardParkFragment.this, phoneEt.getText().toString())) {
                            BToast.showText(AddMonthCardParkFragment.this, "请填写正确的手机号");
                            return;
                        }
                        if (isImage != 0 && !imageList.get(0).equals("0")) {
                            upImagePresenter.upImage();
                        } else {
                            BToast.showText(AddMonthCardParkFragment.this, "请上传驾驶证");
                        }
                    }
                }
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    private void initViewBind() {
        submitTv.setText("提交");
        imageTv.setText("请上传驾驶证");
        communityEt.setText(getIntent().getExtras().getString("parkName"));
        carEt.setText(getIntent().getExtras().getString("carId"));

        imageRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        repairImageAdapter = new RepairImageAdapter(this);
        imageRecyclerView.setAdapter(repairImageAdapter);
        imageList.add(0, "0");
        repairImageAdapter.setNewData(imageList);
        repairImageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                onClickCamera();
            }
        });
    }

    @Override
    public void permissionGrant(boolean isGranted, int requestCode) {
        super.permissionGrant(isGranted, requestCode);
        if (!isGranted) {
            return;
        }
        switch (requestCode) {
            case 0x0001://拍照
                VanGogh.from(AddMonthCardParkFragment.this)
                        .choose(VanMediaType.ofAll())//拍照时，无效
                        .cameraVisible(true, getPackageName())//拍照时，第一个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_ActivityAnimation)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forCamera(REQUEST_CODE_CAMERA);
                break;

            case 0x0002://从相册选择
                VanGogh.from(AddMonthCardParkFragment.this)
                        .choose(VanMediaType.ofAll())
                        .countable(true)//若开启裁剪，则无效
                        .maxCount(1)
                        .rowCount(3)
                        .cameraVisible(true, getPackageName())//设置在第一个参数为FALSE时，第二个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为TRUE时，则可选中数量被设为1，此时maxSelectable(9)无效；第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_Dracula)
                        .addFilter(new GifSizeFilter(320, 320, 5 * VanMediaFilter.K * VanMediaFilter.K))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;

            default:
                break;
        }
    }

    @OnClick({R.id.head_back, R.id.fragment_add_month_card_park_project})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_back:
                finish();
                break;
            case R.id.fragment_add_month_card_park_project:
                Bundle bundle = new Bundle();
                bundle.putInt("type", Contants.CHOOSECOMMUNITYCERTIFITION);
                startIntentActivityForResult(ResidentCertificationActivity.class, bundle, Contants.CHOOSECOMMUNITYCERTIFITION);

                break;
        }
    }

    ResidentBean residentBean;
    String roomId;
    String projectedId;
    int idType;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList = new ArrayList<>();
            switch (requestCode) {
                case Contants.CHOOSECOMMUNITYCERTIFITION:
                    if (data.getExtras().getString("community") != null) {
                        residentBean = new Gson().fromJson(data.getExtras().getString("community"), ResidentBean.class);
                        ResidentCertificationBean.ResultBean.RoomCheckUserListBean video = (ResidentCertificationBean.ResultBean.RoomCheckUserListBean) residentBean.t;
                        roomId = video.getRoomId();
                        idType = video.getIdType();
                        projectedId = video.getProjectId();
                        projectEt.setText(data.getExtras().getString("title") + "\n" + video.getAddress());
                    }
                    break;
                case REQUEST_CODE_CHOOSE:
                    if (VanGogh.obtainResult(data) != null) {
                        if (VanGogh.obtainResult(data).size() > 0) {
                            for (int i = 0; i < VanGogh.obtainResult(data).size(); i++) {
                                pathList.add(GetImagePathUtil.getRealFilePath(this, VanGogh.obtainResult(data).get(i)));
                            }
                        }
                    }
                    if (pathList != null) {
                        imageList.set(0, pathList.get(0));
                    }
                    isImage = 1;
                    repairImageAdapter.setNewData(imageList);
                    break;
                case REQUEST_CODE_CAMERA:
                    Uri contentUri = VanGogh.obtainCamera();
                    if (contentUri == null) {
                        return;
                    }

                    if (!VanConfig.getInstance().cropEnable) {

                        pathList.add(GetImagePathUtil.getRealFilePath(this, contentUri));
                    }
                    if (pathList != null) {
                        imageList.set(0, pathList.get(0));
                    }
                    isImage = 1;
                    repairImageAdapter.setNewData(imageList);
                    break;
            }
        }
    }

    /**
     * 判断是否可以请求数据
     */
    String token, userId, userName;
    int urlType;

    private boolean isLogin() {

        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
        } else {
            BToast.showText(this, "请先登录");
            return false;
        }

        return true;
    }

    @Override
    public String header() {
        return getIntent().getExtras().getString("tenantId");
    }

    @Override
    public List<String> imageList() {
        return imageList;
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public String userId() {
        return userId;
    }

    @Override
    public String parkInfoId() {
        return getIntent().getExtras().getString("parkInfoId");
    }

    @Override
    public String carId() {
        return getIntent().getExtras().getString("carId");
    }

    @Override
    public Integer carType() {
        return 1;
    }

    @Override
    public String projectId() {
        return projectedId;
    }

    @Override
    public String exclusiveFlag() {
        return "";
    }

    @Override
    public String monthCarType() {
        return "";
    }

    @Override
    public String roomId() {

        return roomId;
    }

    @Override
    public String owner() {
        return nameEt.getText().toString().trim();
    }

    @Override
    public String mobile() {
        return phoneEt.getText().toString().trim();
    }

    @Override
    public String images() {
        return attachFile;
    }

    @Override
    public String remark() {
        return "";
    }

    @Override
    public Integer idType() {
        return idType;
    }

    @Override
    public String filed1() {
        return "";
    }

    @Override
    public String id() {
        return null;
    }

    @Override
    public String startTime() {
        return null;
    }

    @Override
    public String orderId() {
        return null;
    }

    @Override
    public String licensePlate() {
        return null;
    }

    @Override
    public void showToast(String content) {
        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {

    }

    String attachFile;

    @Override
    public void getData(UpImageBean upImageBean) {
        attachFile = upImageBean.getResult();
        Log.i("testImage", isImage + "");
        if (attachFile != null) {
            if (isImage == 1) {
                parkingPresenter.addMonthCar();
            } else {
                BToast.showText(this, "请上传驾驶证");
            }
        }
    }

    @Override
    public void showProgress() {
        showLoding();
    }

    @Override
    public void hideProgress() {
        hideLoding();
    }

    @Override
    public void getMsg(GetParkingBean getParkingBean) {

    }

    @Override
    public void getMsg(CheckMonthParkBean checkMonthParkBean) {

    }

    @Override
    public void getMsg(AddMonthCarBean addMonthCarBean) {
//        if (addMonthCarBean.getMessage() != null) {
        BToast.showText(this, addMonthCarBean.getMessage());
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt("finish", 1);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            finish();
//        }
    }

    @Override
    public void getMsg(GetMonthCarListBean getMonthCarListBean) {

    }

    @Override
    public void getMsg(PaymentsBean paymentsBean) {

    }

    @Override
    public void getMsg(ComputeParkingBean computeParkingBean) {

    }

    @Override
    public void getMsg(FeeListBean feeListBean) {

    }

    @Override
    public void removeImage(int position) {
        imageList.set(0, "0");
        isImage = 0;
        repairImageAdapter.setNewData(imageList);
    }
}
